package com.qk.management.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.dto.operateLog.operateLogDTO;
import com.qk.entity.OperateLog;
import com.qk.entity.User;
import com.qk.management.mapper.OperateLogMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.OperateLogService;
import com.qk.vo.operateLog.OperateLogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Wrapper;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 *
 * @author blusr
 * @version 1.0
 * @date 2025/10/17 17:05
 */
@Service
public class OperateLogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLog> implements OperateLogService {
    @Autowired
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public PageResult<OperateLogVO> getOperatePage(operateLogDTO dto) {
        LambdaQueryWrapper<OperateLog> queryWrapper = Wrappers.lambdaQuery(OperateLog.class).orderByDesc(OperateLog::getOperateTime);
        if (ObjectUtil.isNotEmpty(dto.getOperateUserName()) && ObjectUtil.notEqual(dto.getOperateUserName(),"")) {
            queryWrapper.eq(OperateLog::getOperateUserId, userMapper.selectUserByName(dto.getOperateUserName()).getId());
        }
        Page<OperateLog> page = page(new Page<>(dto.getPage(), dto.getPageSize()), queryWrapper);
        List<OperateLogVO> collect = page.getRecords().stream().map(operateLog ->{
                OperateLogVO vo = BeanUtil.copyProperties(operateLog, OperateLogVO.class);
                User user = userMapper.selectById(operateLog.getOperateUserId());
                vo.setOperateUserName(ObjectUtil.isNotEmpty(user)?user.getName():"");
                return vo;
            }
        ).toList();
        return PageResult.<OperateLogVO>builder()
                .total(page.getTotal())
                .rows(collect)
                .build();
    }
}
